from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponse
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser

from apps.core.models import ProcessingTask, UploadedFile, Template
from apps.core.serializers import ProcessingTaskSerializer, UploadedFileSerializer
from apps.core.services import data_processing_service, task_queue_service
from apps.core.utils import generate_unique_filename, get_file_info


@login_required
def data_upload(request):
    """数据上传页面"""
    return render(request, 'data_processing/data_upload.html')


@login_required
def data_generation(request):
    """数据生成页面"""
    # 获取所有启用的模板
    templates = Template.objects.filter(is_active=True).order_by('-created_at')
    context = {
        'templates': templates
    }
    return render(request, 'data_processing/data_generation.html', context)





@login_required
def task_list(request):
    """任务列表页面"""
    return render(request, 'data_processing/task_list.html')


@login_required
def task_detail(request, task_id):
    """任务详情页面"""
    task = get_object_or_404(ProcessingTask, id=task_id)
    return render(request, 'data_processing/task_detail.html', {'task': task})


@login_required
def task_status_view(request):
    """任务状态页面"""
    return render(request, 'data_processing/task_status.html')





class TaskAPIView(APIView):
    """任务管理API"""
    permission_classes = [IsAuthenticated]
    
    def get(self, request, task_id=None):
        """获取任务信息"""
        if task_id:
            try:
                task = ProcessingTask.objects.get(id=task_id)
                serializer = ProcessingTaskSerializer(task)
                return Response(serializer.data, status=status.HTTP_200_OK)
            except ProcessingTask.DoesNotExist:
                return Response({
                    'error': '任务不存在'
                }, status=status.HTTP_404_NOT_FOUND)
        else:
            # 获取任务列表
            tasks = ProcessingTask.objects.filter(created_by=request.user).order_by('-created_at')
            
            # 分页
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            start = (page - 1) * page_size
            end = start + page_size
            
            total = tasks.count()
            tasks_page = tasks[start:end]
            
            serializer = ProcessingTaskSerializer(tasks_page, many=True)
            
            return Response({
                'tasks': serializer.data,
                'total': total,
                'page': page,
                'page_size': page_size,
                'total_pages': (total + page_size - 1) // page_size
            }, status=status.HTTP_200_OK)
    
    def post(self, request):
        """创建新任务"""
        try:
            import json
            
            # 获取请求数据
            template_id = request.data.get('template_id')
            files = request.FILES.getlist('files')
            file_configs_str = request.data.get('file_configs', '[]')
            task_name = request.data.get('description', '数据处理任务')
            
            if not template_id:
                return Response({
                    'error': '请选择模板'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            if not files:
                return Response({
                    'error': '请选择要处理的文件'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 解析文件配置
            try:
                file_configs = json.loads(file_configs_str)
            except json.JSONDecodeError:
                file_configs = []
            
            # 创建任务
            task = ProcessingTask.objects.create(
                task_name=task_name,
                template_id=template_id,
                created_by=request.user,
                status='pending'
            )
            
            # 处理上传的文件
            uploaded_file_ids = []
            for i, uploaded_file in enumerate(files):
                # 获取对应的文件配置
                file_config = next((config for config in file_configs if config.get('index') == i), {})
                
                # 生成唯一文件名
                unique_filename = generate_unique_filename(uploaded_file.name)
                
                # 创建UploadedFile记录
                file_obj = UploadedFile.objects.create(
                    original_name=uploaded_file.name,
                    file_size=uploaded_file.size,
                    file_type=file_config.get('file_type', 'source'),
                    source_name=file_config.get('source_name', ''),
                    task=task,
                    created_by=request.user
                )
                
                # 保存文件
                file_obj.file.save(unique_filename, uploaded_file)
                uploaded_file_ids.append(file_obj.id)
            
            # 提交到任务队列（如果服务存在）
            try:
                task_queue_service.submit_task(task.id)
            except:
                pass  # 如果任务队列服务不可用，忽略错误
            
            return Response({
                'message': '任务创建成功',
                'id': str(task.id),
                'task': ProcessingTaskSerializer(task).data
            }, status=status.HTTP_201_CREATED)
            
        except Exception as e:
            return Response({
                'error': f'创建任务失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def cancel_task(request, task_id):
    """取消任务"""
    try:
        task = ProcessingTask.objects.get(id=task_id, created_by=request.user)
        
        if task.status in ['completed', 'failed', 'cancelled']:
            return Response({
                'error': '任务已完成或已取消，无法取消'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 取消任务
        task.status = 'cancelled'
        task.save()
        
        # 从队列中移除
        task_queue_service.cancel_task(task_id)
        
        return Response({
            'message': '任务已取消'
        }, status=status.HTTP_200_OK)
        
    except ProcessingTask.DoesNotExist:
        return Response({
            'error': '任务不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'error': f'取消任务失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def retry_task(request, task_id):
    """重试任务"""
    try:
        task = ProcessingTask.objects.get(id=task_id, created_by=request.user)
        
        if task.status not in ['failed', 'cancelled']:
            return Response({
                'error': '只能重试失败或已取消的任务'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 重置任务状态
        task.status = 'pending'
        task.error_message = ''
        task.save()
        
        # 重新提交到队列
        task_queue_service.submit_task(task_id)
        
        return Response({
            'message': '任务已重新提交'
        }, status=status.HTTP_200_OK)
        
    except ProcessingTask.DoesNotExist:
        return Response({
            'error': '任务不存在'
        }, status=status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return Response({
            'error': f'重试任务失败: {str(e)}'
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
